<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<u-icon name="search" color="#909399" size="30"></u-icon>
				<input 
                    type="text" 
                    class="search-input" 
                    placeholder="请输入姓名或手机号" 
                    v-model="searchKeyword"
                    @confirm="handleSearch"
                    confirm-type="search"
                 />
			</view>
			<button class="search-button" @click="handleSearch">搜索</button>
		</view>

		<!-- 最近兑换 -->
		<view class="section-title" v-if="hiddenList">最近兑换</view>
		<view class="recent-list" v-if="hiddenList">
            <!-- 加载提示 -->
            <view v-if="loadingRecent" class="loading-placeholder">加载中...</view>
            <!-- 空列表提示 -->
            <view v-else-if="recentAllyList.length === 0" class="empty-placeholder">
                暂无最近兑换记录
            </view>
            <!-- 列表项 -->
            <view v-else>
                <view v-for="ally in recentAllyList" :key="ally.id" class="ally-item" @click="selectAllyItem(ally)">
                     <image class="avatar" :src="ally.imgUrl || '/static/img/default_avatar.png'" mode="aspectFill"></image>
                     <view class="info">
                        <text class="name">{{ ally.userName }}</text>
                        <text class="phone">{{ ally.phone }}</text>
                     </view>
                </view>
            </view>
		</view>

		<!-- 搜索结果 -->
        <view class="section-title" v-if="!hiddenList">搜索结果</view> 
		<view class="ally-list" v-if="!hiddenList">
			<!-- 加载提示 -->
            <view v-if="loadingSearch" class="loading-placeholder">加载中...</view>
            <!-- 空列表提示 -->
			<view v-else-if="allyList.length === 0 && searchPerformed" class="empty-placeholder">
				未搜索到结果
			</view>
             <view v-else-if="allyList.length === 0 && !searchPerformed" class="empty-placeholder">
				请输入关键词进行搜索
			</view>
			<!-- 列表项 -->
			<view v-else>
                <view v-for="ally in allyList" :key="ally.id" class="ally-item" @click="selectAllyItem(ally)">
                     <image class="avatar" :src="ally.imgUrl || '/static/img/default_avatar.png'" mode="aspectFill"></image>
                     <view class="info">
                        <text class="name">{{ ally.userName }}</text>
                        <text class="phone">{{ ally.phone }}</text>
                     </view>
                </view>
            </view>
		</view>
	</view>
</template>

<script>
const api = require('../../../config/api'); 
const util = require('../../../utils/util');

export default {
	data() {
		return {
			searchKeyword: '',
			hiddenList: true,
			allyList: [], // 搜索结果列表
			recentAllyList: [], // 最近兑换列表
            loadingSearch: false, 
            loadingRecent: false,
            searchPerformed: false, // 标记是否执行过搜索
		};
	},
	onLoad() {
        this.fetchRecentAllies();
	},
	methods: {
        // 处理搜索
		handleSearch() {
            if (!this.searchKeyword) {
                uni.showToast({ title: '请输入搜索关键词', icon: 'none' });
                return;
            }
			console.log('搜索关键词:', this.searchKeyword);
            this.allyList = []; // 清空旧列表
            this.loadingSearch = true;
            this.searchPerformed = true;
			this.hiddenList=false;
            this.fetchAllyList();
		},

        // 获取盟友列表 (根据关键词搜索)
        async fetchAllyList() {
            const token = uni.getStorageSync('token');
            if (!token) {
                uni.showToast({ title: '请先登录', icon: 'none' });
                this.loadingSearch = false;
                return;
            }
            
            try {
                // 使用util.request请求方式
                const res = await util.request(
                    api.searchExchangeObjectUrl + '/' + this.searchKeyword,
                    {},
                    'POST'
                );
                
                console.log('搜索盟友列表结果:', res);
                
                if (res.code === 0) {
                    this.allyList = res.data || [];
                } else {
                    uni.showToast({ title: res.msg || '搜索失败', icon: 'none' });
                    this.allyList = [];
                }
            } catch (error) {
                console.error("搜索盟友列表失败:", error);
                uni.showToast({ title: '网络错误', icon: 'none' });
                this.allyList = [];
            } finally {
                this.loadingSearch = false;
            }
        },

        // 获取最近兑换盟友
        async fetchRecentAllies() {
             const token = uni.getStorageSync('token');
             if (!token) {
                 // 最近兑换非强制，可以不提示
                 this.loadingRecent = false;
                 return;
             }
             this.loadingRecent = true;
			 console.log(api.recentExchangeObjectUrl);
             try {
                // 使用util.request请求方式
                const res = await util.request(
                    api.recentExchangeObjectUrl,
                    {},
                    'POST'
                );
                
                console.log('获取最近兑换列表结果:', res);
                
                if (res.code === 0) {
                    this.recentAllyList = res.data || [];
                } else {
                    // 不提示错误，避免干扰
                    console.log('加载最近记录失败:', res.msg);
                    this.recentAllyList = [];
                }
             } catch (error) {
                console.error("获取最近兑换列表失败:", error);
                this.recentAllyList = [];
                // uni.showToast({ title: '网络错误', icon: 'none' });
             } finally {
                 this.loadingRecent = false;
             }
        },

		// 选择盟友并返回
		selectAllyItem(ally) {
			console.log('选择了盟友:', ally);
            // 确保传递给上一页的数据包含必要字段 (id 和 name/userName)
            const selectedAllyData = {
                id: ally.id,
                name: ally.userName // 与RedeGoodsDetails中期望的字段匹配
            };
            
			const pages = getCurrentPages();
			if (pages.length >= 2) {
                uni.$emit('selectAllyEvent', { ally: selectedAllyData });
				uni.navigateBack(); 
			} else {
                console.error('无法获取上一页');
                uni.showToast({ title: '选择失败，请重试', icon: 'none' });
            }
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #fff;
}

/* --- 复用 SelectAlly 的搜索栏样式 --- */
.search-bar {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff; 
    border-bottom: 1rpx solid #f5f5f5;

	.search-input-wrapper {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #f5f5f5; 
		border-radius: 30rpx;
		padding: 10rpx 25rpx;
		margin-right: 20rpx;

		.search-input {
			flex: 1;
			font-size: 28rpx;
			margin-left: 10rpx;
            height: 40rpx; 
            line-height: 40rpx;
		}
	}

	.search-button {
		background-color: transparent; 
        color: #333; 
        border: none;
        padding: 0 10rpx; 
        margin: 0;
        font-size: 30rpx;
        height: 60rpx; 
        line-height: 60rpx;
        &::after {
            border: none;
        }
	}
}
/* --- 搜索栏样式结束 --- */

.section-title {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	padding: 30rpx 30rpx 15rpx 30rpx;
    background-color: #f9f9f9; // 给标题加个背景区分
    border-bottom: 1rpx solid #f5f5f5;
    border-top: 1rpx solid #f5f5f5;
}

.ally-list, .recent-list {
	// padding: 0 30rpx; // 移除左右 padding，让 ally-item 占满宽度
}

.ally-item {
    display: flex;
    align-items: center;
    padding: 25rpx 30rpx; // 列表项的左右 padding
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
        border-bottom: none;
    }

    .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        background-color: #eee; 
        flex-shrink: 0;
    }

    .info {
        display: flex;
        flex-direction: column;
        min-width: 0; // 防止内容撑开
        .name {
            font-size: 30rpx;
            color: #333;
            margin-bottom: 5rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .phone {
            font-size: 26rpx;
            color: #999;
        }
    }
}

.loading-placeholder, .empty-placeholder {
	text-align: center;
	color: #999;
	font-size: 28rpx;
	padding: 80rpx 0;
}

</style> 